<?php

namespace api\controllers;

use api\components\PaysRed;
use api\components\PaysToUser;
use api\components\PayToUser;
use api\components\WeChatPublic;
use api\models\PubUser;
use api\service\WechatService;
use Yii;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\Cors;

class WechatController extends ActiveController
{
    public $modelClass = '';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 86400,
            ],
        ];
        return $behaviors;
    }

    //微信服务接入时，服务器需授权验证
    public function actionValid()
    {
        $request = Yii::$app->request;
        $echoStr = $request->get('echostr');
        $signature = $request->get('signature');
        $timestamp = $request->get('timestamp');
        $nonce = $request->get('nonce');
        //$echoStr = $_GET["echostr"] ? $_GET['echostr'] : '';
        //$signature = $_GET["signature"] ? $_GET['signature'] : '';
        //$timestamp = $_GET["timestamp"] ? $_GET['timestamp'] : '';
        //$nonce = $_GET["nonce"] ? $_GET['nonce'] : '';
        //valid signature , option
        //file_put_contents('./logall.txt',$_GET,FILE_APPEND);
        if (!isset($echoStr)) {
            //$this->responseMsg();
            $this->custom();
        } else {
            if ($this->checkSignature($signature, $timestamp, $nonce)) {
                echo $echoStr;
            }
        }
    }

    public function responseMsg()
    {
        //1.获取到微信推送过来post数据（xml格式）
//        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        $postArr = file_get_contents("php://input");
        //2.处理消息类型，并设置回复类型和内容
        $postObj = simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA);
        file_put_contents('./log.txt', $postArr, FILE_APPEND);
        //判断该数据包是否是订阅de事件推送
//        if (strtolower($postObj->MsgType) == 'event') {
        //如果是关注 subscribe事件
//            if (strtolower($postObj->Event) == 'subscribe') {
        $toUser = $postObj->FromUserName;
        $fromUser = $postObj->ToUserName;
        $time = time();
        $msgType = 'text';
        $content = '您好！';
        $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
        $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
        echo $info;
//            }
//        }
    }


    //参数校验
    private function checkSignature($signature, $timestamp, $nonce)
    {
        $token = Yii::$app->params['wechat']['token'];
        if (!$token) {
            echo 'TOKEN is not defined!';
        } else {
            $tmpArr = array($token, $timestamp, $nonce);
            // use SORT_STRING rule
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                return true;
            } else {
                return false;
            }
        }
    }

    public function custom()
    {
        $WechatService = new WechatService();
        $WechatPublic = new WeChatPublic();
        $access_token = $WechatPublic->getAccessToken();
        $postStr = file_get_contents("php://input");
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        if (!empty($postObj)) {
            $toUser = $postObj->FromUserName;
            $fromUser = $postObj->ToUserName;
            $time = time();
            $msgType = 'text';
            $content = '😀';
            $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
            echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
        }


        /*
    if (!empty($postStr) && is_string($postStr)) {
        $postArr = json_decode($postStr, true);

        if (!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text') {
            //文本消息
            $fromUsername = $postArr['FromUserName'];   //发送者openid
            $toUserName = $postArr['ToUserName'];       //小程序id
            if (strpos($postArr['Content'], '1') !== false) {
                $media_id = $WechatService->upload_meterial(realpath('https://publicy-1258261086.cos.ap-guangzhou.myqcloud.com/qrcode/qrcode_xiu_20190420152140.jpg'), $access_token);
                $data = array(
                    "touser" => $fromUsername,
                    "msgtype" => "image",
                    "image" => array("media_id" => $media_id)
                );
                $WechatService->replySpecial($data, $access_token);
                exit;
            }
            $textTpl = array(
                "ToUserName" => $fromUsername,
                "FromUserName" => $toUserName,
                "CreateTime" => time(),
                "MsgType" => "transfer_customer_service",
                'TransInfo' => array('KfAccount' => 'surpacc'),
            );
            exit(json_encode($textTpl));
        } elseif (!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image') { //图文消息
            $fromUsername = $postArr['FromUserName'];   //发送者openid
            $toUserName = $postArr['ToUserName'];       //小程序id
            $textTpl = array(
                "ToUserName" => $fromUsername,
                "FromUserName" => $toUserName,
                "CreateTime" => time(),
                "MsgType" => "transfer_customer_service",
                'TransInfo' => array('KfAccount' => 'surpacc'),
            );

            exit(json_encode($textTpl));
        } elseif ($postArr['MsgType'] == 'event' && $postArr['Event'] == 'user_enter_tempsession') { //进入客服动作

            $fromUsername = $postArr['FromUserName'];   //发送者openid

            //发送小程序卡片
//				$thumb_media_id = $this->upload_meterial();
//				$data = array(
//					"touser" => $fromUsername,
//					"msgtype" => "miniprogrampage",
//					"miniprogrampage" => array(
//						"title" =>"Happy Day",
//						"pagepath"=> "pages/index/index",
//						"thumb_media_id"=> $thumb_media_id,
//					)
//				);

//              //发送图文链接
//                $data = array(
//                    "touser" => $fromUsername,
//                    "msgtype" => "link",
//                    "link" => array(
//                        "title" =>"壁虎淘车",
//                        "description"=> "您好，有什么可以帮助您？",
//                        "url"=> "http://thread.chebihu.com",
//                        "thumb_url"=> "http://auction.chebihu.com/yazai.jpg"
//                    )
//                );

            //发送图片
            //$media_id = $this->upload_meterial();
            //file_put_contents('oojson'.date("Y-m-d").'.txt',print_r($media_id,true).PHP_EOL,FILE_APPEND);
            //$data = array(
//                        "touser" => $fromUsername,
//                        "msgtype" => "image",
//                        "image" => array("media_id"=>$media_id)
//                );
            //发送文字
            $content = '欢迎！';
            $data = array(
                "touser" => $fromUsername,
                "msgtype" => "text",
                "text" => array("content" => $content)
            );
            $WechatService->replySpecial($data, $access_token);
            $media_id = $this->upload_meterial(realpath('./images/pick.jpg'));
            $data = array(
                "touser" => $fromUsername,
                "msgtype" => "image",
                "image" => array("media_id"=>$media_id)
            );
            $this->replySpecial($data);
            echo 'success';
            exit;
            //$this->transfer_customer_service->reply();

        } else {
            exit('error2');
        }
    } else {
        echo "error1";
        exit;
    }
    **/
    }


    /**
     * 获取用户信息资料
     */
    public
    function actionUser()
    {
        $request = Yii::$app->request;
        $isCode = $request->get('iscode');
        $code = $request->get('code');
        $WeChat = new WeChatPublic();
        if ($isCode) {
            $url = "https://teach.idwenshi.com/teach/api/web/index.php/wechat/user";
            $result = $WeChat->getRequestCodeURL($url);
            header("Location:{$result}");
        } elseif ($code) {
            //获取网页版access_token openid unionid
            $user = $WeChat->getAccessToken('code', $code);
            //通过openid 获取用户信息
            $userDetail = $WeChat->getUser($user['openid'], $user['access_token']);
            $userCheck = PubUser::find()->where(['openid' => $userDetail['openid']])->one();
            $time = time();
            if ($userCheck) {
                $userCheck->nickname = $userDetail['nickname'];
                $userCheck->headimgurl = $userDetail['headimgurl'];
                $userCheck->sex = $userDetail['sex'];
                $userCheck->unionid = $userDetail['unionid'];
                $userCheck->city = $userDetail['city'];
                $userCheck->province = $userDetail['province'];
                $userCheck->update_time = $time;
                $userCheck->save();
                $id = $userCheck->id;
            } else {
                $userNew = new PubUser();
                $userNew->openid = $userDetail['openid'];
                $userNew->nickname = $userDetail['nickname'];
                $userNew->headimgurl = $userDetail['headimgurl'];
                $userNew->sex = $userDetail['sex'];
                $userNew->unionid = $userDetail['unionid'];
                $userNew->city = $userDetail['city'];
                $userNew->province = $userDetail['province'];
                $userNew->update_time = $time;
                $userNew->create_time = $time;
                $userNew->save();
                $id = $userNew->id;
            }
            if ($userDetail['openid']) {
                //查找用户
                $WechatService = new WechatService();
                $user = $WechatService->userPubMin($id);
                //file_put_contents('./log.txt',json_encode($user),FILE_APPEND);
                if ($user) {
                    if ($user['mall_is'] == 1) {
                        $shopUrl = "https://teach.idwenshi.com/publicy/xiuexuewen2/dist/pages/indexshop.html?uid={$user['pub_id']}";
                        header("Location:{$shopUrl}");
                    } else {
                        $userUrl = "https://teach.idwenshi.com/publicy/xiuexuewen2/dist/pages/index.html?uid={$user['pub_id']}";
                        header("Location:{$userUrl}");
                    }
                } else {
                    $qrUrl = "https://teach.idwenshi.com/publicy/xiuexuewen2/dist/pages/404.html";
                    header("Location:{$qrUrl}");
                }
            }
        }
        return;
    }

    public
    function actionMenuSet()
    {
        $map = '{
            "button": [
            {
                "name": "小程序",
                "sub_button": [
                {
                    "type": "miniprogram",
                    "name": "绣学问商城",
                    "url": "http://mp.weixin.qq.com",
                    "appid": "wxb1f5224c98168afc",
                    "pagepath": "shopPage/shoppages/index/index"
                },
                {
                    "type": "miniprogram",
                    "name": "鲨宝宝商城",
                    "url": "http://mp.weixin.qq.com",
                    "appid": "wx9f5e0a4d343331a4",
                    "pagepath": "pages/menu/menu"
                }
                ]
            },
            {
                "name": "用户中心",
                "sub_button": [
                {
                    "type": "view",
                    "name": "我的账号",
                    "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb9542e9e06324ddd&redirect_uri=https://teach.idwenshi.com/teach/api/web/index.php/wechat/user&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect",
                }
                ]
            },
            ]
        }';

        $map = '{
            "button": [
            {
                "name": "小程序",
                "sub_button": [
                {
                    "type": "miniprogram",
                    "name": "绣学问商城",
                    "url": "http://mp.weixin.qq.com",
                    "appid": "wxb1f5224c98168afc",
                    "pagepath": "shopPage/shoppages/index/index"
                },
                {
                    "type": "miniprogram",
                    "name": "鲨宝宝商城",
                    "url": "http://mp.weixin.qq.com",
                    "appid": "wx9f5e0a4d343331a4",
                    "pagepath": "pages/menu/menu"
                }
                ]
            } 
            ]
        }';

        $WeChatPublic = new WeChatPublic();
        $res = $WeChatPublic->setMenu($map);
        return $this->asJson($res);
    }

    /**单一商户号企业付款到零钱
     * 企业付款零钱
     */
    public function actionChange()
    {
        /**
         * array(7) {
         * ["return_code"]=>
         * string(7) "SUCCESS"
         * ["return_msg"]=>
         * string(12) "支付失败"
         * ["mch_appid"]=>
         * string(18) "wxb1f5224c98168afc"
         * ["mchid"]=>
         * string(10) "1522943571"
         * ["result_code"]=>
         * string(4) "FAIL"
         * ["err_code"]=>
         * string(9) "NOTENOUGH"
         * ["err_code_des"]=>
         * string(12) "余额不足"
         * }
         *
         *
         * array(9) {
         * ["return_code"]=>
         * string(7) "SUCCESS"
         * ["return_msg"]=>
         * array(0) {
         * }
         * ["mch_appid"]=>
         * string(18) "wxb1f5224c98168afc"
         * ["mchid"]=>
         * string(10) "1522943571"
         * ["nonce_str"]=>
         * string(32) "1dad9eba7b2f731661b60d178f2c40ff"
         * ["result_code"]=>
         * string(7) "SUCCESS"
         * ["partner_trade_no"]=>
         * string(32) "15550580431555058043155505804383"
         * ["payment_no"]=>
         * string(28) "1522943571201904128596144866"
         * ["payment_time"]=>
         * string(19) "2019-04-12 16:34:04"
         * }
         */
        $pay = new PayToUser();
        $openid = "oLAZ75aa9tYmJB3mIaLzMfOBcAkA";
        $amount = 0.3;
        $result = $pay->send($openid, $amount);
        var_dump($result);

    }

    /**
     * 兼容多商户号企业付款到零钱
     * 企业付款零钱
     */
    public function actionPaysUser()
    {
        /**
         * array(7) {
         * ["return_code"]=>
         * string(7) "SUCCESS"
         * ["return_msg"]=>
         * string(12) "支付失败"
         * ["mch_appid"]=>
         * string(18) "wxb1f5224c98168afc"
         * ["mchid"]=>
         * string(10) "1522943571"
         * ["result_code"]=>
         * string(4) "FAIL"
         * ["err_code"]=>
         * string(9) "NOTENOUGH"
         * ["err_code_des"]=>
         * string(12) "余额不足"
         * }
         *
         *
        array(9) {
        ["return_code"]=>
        string(7) "SUCCESS"
        ["return_msg"]=>
        array(0) {
        }
        ["mch_appid"]=>
        string(18) "wxb1f5224c98168afc"
        ["mchid"]=>
        string(10) "1528785111"
        ["nonce_str"]=>
        string(32) "976bec79477a598eddb7777916be6b59"
        ["result_code"]=>
        string(7) "SUCCESS"
        ["partner_trade_no"]=>
        string(25) "Ca20190626156153535982727"
        ["payment_no"]=>
        string(28) "1528785111201906269529149398"
        ["payment_time"]=>
        string(19) "2019-06-26 15:49:20"
        }
         * }
         */
        $mid = 10000;
        $appid = Yii::$app->params['serviceNum'][$mid]['sub_appid'];
        $openid = "oLAZ75aa9tYmJB3mIaLzMfOBcAkA";
        $mch_id = Yii::$app->params['serviceNum'][$mid]['sub_mch_id'];
        $key = Yii::$app->params['serviceNum'][$mid]['md5Key'];
        $out_trade_no = 'Ca' . date('Ymd') .time() .str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $body = '测试提现';
        $total_fee = 1;
        $spbill_create_ip = $_SERVER['REMOTE_ADDR'];
        $paysToUser = new PaysToUser($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $spbill_create_ip, $mid);
        $result = $paysToUser->send();
        var_dump($result);

    }

    /**
     * 服务商模式红包支付
     */
    public function actionPays()
    {
        /**
         * string(573) "<xml>
        <return_code><![CDATA[SUCCESS]]></return_code>
        <return_msg><![CDATA[发放成功]]></return_msg>
        <result_code><![CDATA[SUCCESS]]></result_code>
        <err_code><![CDATA[SUCCESS]]></err_code>
        <err_code_des><![CDATA[发放成功]]></err_code_des>
        <mch_billno><![CDATA[Red20190614156050132866933]]></mch_billno>
        <mch_id><![CDATA[1528625341]]></mch_id>
        <wxappid><![CDATA[wxb9542e9e06324ddd]]></wxappid>
        <re_openid><![CDATA[oLAZ75aa9tYmJB3mIaLzMfOBcAkA]]></re_openid>
        <total_amount>100</total_amount>
        <send_listid><![CDATA[1000041701201906143000130661454]]></send_listid>
        </xml>"
         *
         * 红包查询可以查找红包退款时间跟领取时间
         * 写一个脚本查询出用户当晚没有领取红包，提醒用户去领取，或者重新发送红包
         * 同一个订单的红包，在发送成功的情况下 近时间不会再发 长时间待测
         */
        $sender = "禧形运色";
        $data = [];
        $data['wxappid'] = 'wxb9542e9e06324ddd';//公众号
        $data['msgappid'] = 'wxb1f5224c98168afc';//子商户appid or 小程序
        $data['mch_id']  = '1528625341';//商户号
        $data['sub_mch_id'] = '1528785111';//子商户号
        $data['mch_billno'] = 'Red' . date('Ymd') .time() .str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
//        $data['mch_billno'] = 'Red' . 111111111111111111;
        $data['re_openid'] = 'oLAZ75aa9tYmJB3mIaLzMfOBcAkA';//接收红包的openid
        $data['total_amount'] = 100;//  单位分， 1元
        $data['total_num'] = 1;//红包数
        $data['send_name'] = $sender;
        $data['wishing'] = '感谢您推送本商城,祝你万事顺意';
        $data['client_ip'] = $_SERVER['REMOTE_ADDR'];
        $data['act_name'] = $sender . '用户奖励回馈';
        $data['remark'] = '推送越多奖励越多';

        $PaysRed = new PaysRed();
        $res = $PaysRed->payLuckyMoney('common', $data);
        var_dump($res);
    }



}